import {
  NavMenuItem,
  NAV_BAR_MENU_PATH,
  SECOND_MENU_PATH
} from './navigationMenu'
import { checkAuth } from '@/utils/methods'

let _ID = 1
const generId = () => _ID++

type MenuDataItem = Omit<NavMenuItem, 'id' | 'children' | 'level'> & {
  id?: number
  children?: MenuDataItem[]
}

/**
 * TODO: 待加权限
 * 文书管理
 */
const WHITE_PATH_LISTS = [
  '/paperwork/template',
  '/paperwork/flow',
  '/paperwork/flow/operate-flow'
]

// 根据权限进行过滤
const filterMenu = (data: MenuDataItem[]) => {
  data.forEach((item) => {
    if (Array.isArray(item.children)) {
      item.children = filterMenu(item.children)
    }
  })

  return data.filter((item) => {
    // 权限数据不完善，暂时不进行权限判断
    return true
    if (
      !item.path ||
      [
        NAV_BAR_MENU_PATH,
        SECOND_MENU_PATH,
        '/paperwork',
        '/paperwork/formDesigner',
        '/systemSetting/tagManagement',
        ...WHITE_PATH_LISTS
      ].includes(item.path)
    ) {
      return true
    }
    if (item.path && item.path !== NAV_BAR_MENU_PATH) {
      return checkAuth(item.path)
    } else if (Array.isArray(item.children)) {
      return item.children.length !== 0
    }
    return false
  })
}

// 设置id
const setMenuItem = (
  data: MenuDataItem[],
  level = 1,
  pid?: number
): NavMenuItem[] => {
  return data.map((item) => {
    const id = generId()
    return {
      ...item,
      id,
      pid: item.pid ?? pid,
      level,
      children: item.children
        ? setMenuItem(item.children, level + 1, id)
        : item.children
    }
  })
}

export const menuHandler = (data: MenuDataItem[]) =>
  setMenuItem(filterMenu(data))

export const generIdMap = (
  data: NavMenuItem[],
  map = new Map<number, NavMenuItem>()
) => {
  data.forEach((item) => {
    map.set(item.id, item)
    if (Array.isArray(item.children)) {
      generIdMap(item.children, map)
    }
  })

  return map
}

export const generPathMap = (
  data: NavMenuItem[],
  map = new Map<string, NavMenuItem>()
) => {
  data.forEach((item) => {
    map.set(item.path, item)
    if (Array.isArray(item.children)) {
      generPathMap(item.children, map)
    }
  })

  return map
}
